package com.qiy.springcloud.alibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.qiy.springcloud.alibaba.controller.service.PaymentService;
import com.qiy.springcloud.entities.CommonResult;
import com.qiy.springcloud.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author wsk
 * @date 2020/3/23 11:09
 */
@RestController
@Slf4j
public class CircleBreakerController {

    private String serverURL = "http://nacos-payment-provider";

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/consumer/fallback/{id}")
//    @SentinelResource(value = "fallback", fallback = "handlerFallback")
    @SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "blockHandler",
            exceptionsToIgnore = {IllegalArgumentException.class})
    public CommonResult<Payment> fallback(@PathVariable("id") Long id) {
        // 调用微服务
        CommonResult<Payment> result = restTemplate.getForObject(serverURL + "/paymentSQL/" + id, CommonResult.class);
        if(id == 5) {
            throw new IllegalArgumentException("非法参数异常");
        } else if(result.getData() == null) {
            throw new NullPointerException("没有找到ID对应的记录，空指针异常");
        }
        return result;
    }

    public CommonResult handlerFallback(@PathVariable("id") Long id,Throwable e) {
        Payment payment = new Payment(id, "null");
        return new CommonResult(444, "兜底异常处理 -> " + e.getMessage(), payment);
    }

    public CommonResult blockHandler(@PathVariable("id") Long id,Throwable e) {
        Payment payment = new Payment(id, "null");
        return new CommonResult(445, "流控兜底 -> " + e.getMessage(), payment);
    }

    @Resource
    private PaymentService paymentService;

    @GetMapping(value = "/consumer/paymentSQL/{id}")
    public CommonResult<Payment> paymentSQL(@PathVariable("id")Long id) {
        return paymentService.pamentSQL(id);
    }
}